import { createApp } from 'vue'
import store from '@/store'
import XShare from '@/components/common/share/x-share.vue'
import WebShare from '@/components/common/share/x-share-pc.vue'
import XSub from '@/components/common/subscribe/index.vue'
import WebSub from '@/components/common/subscribe/web-subscribe.vue'
import ModalForm from '@/components/common/x-modal-form/index.vue'
// import TreeModal from '@/components/common/tree-modal/index.vue'
import MenuTreeModal from '@/components/white-theme/h5/menu-tree/index.vue'
// import WebTreeModal from '@/components/common/tree-modal/web-tree-modal.vue'
import BranchNode from '@/components/common/branch/branch-node.vue'
import BranchPcNode from '@/components/common/branch/branch-pc-node.vue'

import Toast from '@/components/common/toast.vue'
import { equ } from '../../package-env'

class Comp {
  private instance
  private parent
  private comp
  constructor(comp) {
    this.parent = document.createElement('div')
    this.comp = comp
  }
  mount(props = {}) {
    if (this.instance !== null) {
      this.unmount()
    }
    if (equ === 'pc' && this.comp.name !== 'Toast') closeSome()
    this.instance = createApp(this.comp, { ...props, onUnmount: () => this.unmount() })
    this.instance.use(store)
    document.body.appendChild(this.parent)
    this.instance.mount(this.parent)
  }
  unmount() {
    if (!this.instance) return
    this.instance.unmount()
    document.body.removeChild(this.parent)
    this.instance = null
  }
}

const _XShare = new Comp(equ === 'pc' ? WebShare : XShare)
const _XSub = new Comp(equ === 'pc' ? WebSub : XSub)
const _XForm = new Comp(ModalForm)
// const _TreeModal = new Comp(equ === 'pc' ? WebTreeModal : TreeModal)
const _MenuTree = new Comp(MenuTreeModal)
const _BranchNode = new Comp(equ === 'pc' ? BranchPcNode : BranchNode)
const _Toast = new Comp(Toast)

export const useShare = () => _XShare.mount()

export const closeShare = () => {
  _XShare.unmount()
}

export const useSub = () => _XSub.mount()

export const closeSub = () => _XSub.unmount()

export const useForm = (id, isNav) => _XForm.mount({ id, isNav })

export const closeForm = () => _XForm.unmount()

// export const useTreeModal = () => _TreeModal.mount()

// export const closeTreeModal = () => _TreeModal.unmount()

export const useMenuTree = (props?) => _MenuTree.mount(props)

export const closeMenuTree = () => _MenuTree.unmount()

export const useBranch = (option?) => _BranchNode.mount(option)

export const closeBranch = () => _BranchNode.unmount()

export const useTost = (msg, name?, showIcon?) => _Toast.mount({ msg, name, showIcon })

export const closeTost = () => _Toast.unmount()

// 关闭已存在弹窗
export const closeSome = ({ form = false, sub = false } = {}) => {
  // closeTreeModal()
  closeMenuTree()
  closeShare()
  closeMenuTree()
  if (!form) closeForm()
  if (!sub) closeSub()
}